<template>
  <div class="real-sky-issue-wrap">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
      <el-form-item v-if="isMuilUnitUser">
        <el-select filterable @change="getList(1)" v-model="searchForm.organizationId" placeholder="请选择业主单位">
          <el-option
            v-for="item in orgOptions"
            :key="item.organizationId"
            :label="item.shortName"
            :value="item.organizationId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select filterable @change="getList(1)" v-model="searchForm.questionType" placeholder="请选择问题类型">
          <el-option label="全部问题类型" value></el-option>
          <el-option
            v-for="item in questionTypeOptions"
            :key="item.dictKey"
            :label="JSON.parse(item.dictValue).name"
            :value="item.dictKey"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchForm.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="util.intTimePickerOptions()"
          @change="getList(1)"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-select filterable @change="getList(1)" v-model="searchForm.status" placeholder="请选择处理状态">
          <el-option label="全部处理状态" value="-1"></el-option>
          <el-option label="未处理" value="0"></el-option>
          <el-option label="已处理" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="form-search-btn" type="primary" @click="getList(1)">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row class="overview-wrap" :gutter="40">
      <el-col :span="12">
        <div class="item-wrap">
          <p class="item-value color-2">{{ realRiskUnitNumber_1 }}</p>
          <p class="item-title">实时重大问题单位总数</p>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="item-wrap">
          <p class="item-value color-2">{{ realRiskUnitNumber_2 }}</p>
          <p class="item-title">实时重大问题总数</p>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData" ref="mainTable" style="width: 100%">
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column v-if="isMuilUnitUser" prop="organizationName" width="250" label="业主单位"></el-table-column>
      <el-table-column prop="questionTypeName" width="250" label="问题类型"></el-table-column>
      <el-table-column prop="selfDesc" label="描述"></el-table-column>
      <el-table-column label="发生时间" width="250">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" width="150" label="处理状态">
        <template slot-scope="scope">
          <span
            :class="
              'tatus-icon-tags ' +
                util.transhandlerStatusColor(scope.row.status)
            "
          ></span>
          {{ util.transhandlerStatusText(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button @click="showDetail(scope.row)" type="text" size="small">详情</el-button>
          <span v-if="scope.row.status != 1" class="dividing-line">|</span>
          <el-button v-if="scope.row.status != 1" @click="dealWith(scope.row)" type="text" size="small">处理</el-button>
          <span class="dividing-line">|</span>
          <el-button
            @click="
              util.openCallCenter(scope.row.organizationId, scope.row.name, 2,scope.row)
            "
            type="text"
            size="small"
          >电话呼叫</el-button>
        </template>
      </el-table-column>
      <el-table-column type="expand" width="1">
        <template slot-scope="scope">
          <el-tabs type="border-card" :data-row="{ scope }" @tab-click="tabClick">
            <el-tab-pane data-label="base">
              <span slot="label">更多信息</span>
              <el-form label-position="left" class="demo-table-expand">
                <el-form-item label="现场图片">
                  <div v-if="scope.row.picturesUrls||scope.row.aiExtInfo" class="troubleImg">
                    <img
                      v-for="(item, i) in scope.row.picList"
                      :key="i"
                      class="alarm-img"
                      :src="formatPicUrl(item)"
                      @click="onPreview(scope,i)"
                    />
                    <img
                      v-for="(item,i) in scope.row.aiExtInfoList"
                      :key="item.pic"
                      class="alarm-img"
                      :src="formatPicUrl(item.imageInfo.pic)"
                      @click=" onPreview(scope,i+scope.row.picList.length) "
                    />
                  </div>
                  <p v-else>无</p>
                </el-form-item>
                <el-form-item label="描述">
                  <span>
                    {{
                    scope.row.startTime + " " + scope.row.selfDesc
                    }}
                  </span>
                </el-form-item>
                <el-form-item label="处理类型">
                  <span>{{ scope.row.handlerTypeName }}</span>
                </el-form-item>
                <el-form-item label="处理记录">
                  <span>{{ scope.row.remarks }}</span>
                </el-form-item>
                <el-form-item label="完好性缺失明细" v-if="scope.row.integrityData">
                  <div class="integrity">
                    <div v-for="(item,index) in scope.row.integrityData" :key="index">
                      <div>
                        {{item.selfDesc}}
                        <span class="weifuwei" v-if="item.isReset == 0">未复位</span>
                        <span class="yifuwei" v-else>已复位</span>
                      </div>
                    </div>
                    <div v-show="showIntegrityData">更多信息请到接处警查看</div>
                  </div>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane data-label="callrecord">
              <span slot="label">呼叫记录</span>
              <call-record :obj="{ type: 2, id: scope.row.id }"></call-record>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="pageSizeChange"
      @current-change="pageChange"
      :current-page="currentPage"
      :page-sizes="[10, 50, 100]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <el-dialog
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      title="火灾重大问题处理"
      width="600px"
      top="25vh"
      :visible.sync="dialogDealWith"
      @close="closeDealWith"
    >
      <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
          <el-form
            label-position="top"
            :model="dealWithForm"
            :rules="dealWithFormRules"
            ref="dealWithForm"
            @submit.native.prevent
          >
            <input type="hidden" id="rowId" v-model="dealWithForm.id" />
            <el-form-item label="处理类型：" prop="handlerType">
              <el-select v-model="dealWithForm.handlerType" filterable placeholder="请选择处理类型">
                <el-option
                  v-for="item in handlerTypeOptions"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="remarks" label="描述：">
              <el-input type="textarea" :rows="7" v-model="dealWithForm.remarks" placeholder="描述"></el-input>
            </el-form-item>
            <el-form-item label-width="0" class="verifyidentity-button">
              <el-button @click="closeDealWith">取消</el-button>
              <el-button type="primary" @click.stop="confirmDealWith('dealWithForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 视频分析图片预览 -->
    <image-viewer ref="ImageViewer" :origin-list="originList"></image-viewer>
  </div>
</template>

<script>
import util from '@/utils/util'
import { getDictByCode } from '@/api/dic'
import { getOrgList } from '@/api/org'
import {
  getKeyIssueList,
  updateHandleResult,
  getKeyProblemCount,
  getHistoryRecordsByTimeSlot,
} from '@/api/keyIssue'
import CallRecord from '../Common/CallRecord'
import ImageViewer from '@/components/TransAiPic/ImageViewer'

export default {
  name: 'RealTimeKeyIssue',
  components: {
    CallRecord,
    ImageViewer,
  },
  data() {
    return {
      util: util,
      isMuilUnitUser: this.$store.state.userinfo.isMuilUnitUser,
      loading: false,
      orgOptions: [{ organizationId: '', shortName: '全部业主单位' }],
      questionTypeOptions: [],
      searchForm: {
        organizationId: this.$store.state.userinfo.isMuilUnitUser
          ? ''
          : this.$store.state.userinfo.org.id,
        questionType: '',
        time: '',
        status: '-1',
      },
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      integrityData: [],
      total: 0,
      realRiskUnitNumber_1: 0, // 实时重大问题单位总数
      realRiskUnitNumber_2: 0, // 实时重大问题总数
      dialogDealWith: false,
      dealWithForm: {
        id: '',
        handlerType: '',
        remarks: '',
      },
      dealWithFormRules: {
        handlerType: [
          { required: true, message: '请选择处理类型', trigger: 'change' },
        ],
      },
      handlerTypeOptions: [],
      showIntegrityData: false,
      /* 图片预览相关的变量 */
      originList: [],
    }
  },
  created: function () {
    let that = this
    // 绑定下拉框
    if (this.isMuilUnitUser) {
      getOrgList({ queryType: 0 }).then((data) => {
        this.orgOptions.push.apply(this.orgOptions, data.data)
      })
    }
    // 绑定问题类型
    getDictByCode({ code: 65 }).then((res) => {
      that.questionTypeOptions = res.data.dictValueObj
    })
    that.getList()
    // 绑定处理类型
    getDictByCode({ code: 66 }).then((res) => {
      that.handlerTypeOptions = res.data.dictValueObj
    })
  },
  methods: {
    getList(_pageIndex, _pageSize) {
      //获取列表
      if (_pageIndex) {
        this.currentPage = _pageIndex
      }
      if (_pageSize) {
        this.pageSize = _pageSize
      }
      let that = this
      let parames = {
        organizationId: that.searchForm.organizationId,
        questionType: that.searchForm.questionType,
        startTimeStr:
          that.searchForm.time && that.searchForm.time.length > 0
            ? that.searchForm.time[0] + ' 00:00:00'
            : '',
        endTimeStr:
          that.searchForm.time && that.searchForm.time.length > 0
            ? that.searchForm.time[1] + ' 23:59:59'
            : '',
        timeType: 13,
        status: that.searchForm.status, // 处理状态
        isReset: 0, //实时
        queryType: 1,
        pageIndex: that.currentPage - 1,
        pageSize: that.pageSize,
      }
      that.loading = true
      getKeyIssueList(parames).then((res) => {
        that.total = res.total
        that.tableData = res.data.map((n) => {
          n.picList = n.picturesUrls ? n.picturesUrls.split(',') : []
          n.aiExtInfoList = n.aiExtInfo ? JSON.parse(n.aiExtInfo) : []
          return n
        })
        let questionType = false
        for (let i in that.tableData) {
          if (that.tableData[i].questionType == 4) {
            this.getIntegrity(
              that.tableData[i].organizationId,
              that.tableData[i].startTime,
              that.tableData[i].endTime,
              that.tableData[i].id
            )
            questionType = true
          }
        }
        if (questionType) {
          setTimeout(function () {
            that.loading = false
          }, 800)
        } else {
          that.loading = false
        }
      })
      // 获取统计信息
      that.getStatis()
    },
    pageSizeChange(val) {
      //页码切换
      this.getList(1, val)
    },
    pageChange(val) {
      //翻页
      this.getList(val)
    },
    // 详细
    showDetail(row) {
      const $table = this.$refs.mainTable
      $table.toggleRowExpansion(row)
      if (row.isExpand) {
        this.getDetail(row)
      }
      row.isExpand = !row.isExpand //给row一个自定义展开状态
    },
    getIntegrity(id, startTime, endTime, ids) {
      let _this = this
      if (endTime == null) {
        endTime = ''
      }
      if (startTime == null) {
        startTime = ''
      }
      let parames = {
        orgId: id,
        userName: _this.$store.state.userinfo.accountName,
        fireTType: 20,
        startTime: startTime,
        endTime: endTime,
      }
      getHistoryRecordsByTimeSlot(parames).then((res) => {
        if (res.status == 200) {
          if (res.total > 51) {
            _this.showIntegrityData = true
            _this.integrityData = res.data.slice(0, 50)
            _this.tableData.forEach((item) => {
              if (item.id == ids) {
                _this.$set(item, 'integrityData', _this.integrityData)
              }
            })
          } else {
            _this.showIntegrityData = false
            _this.integrityData = res.data
            _this.tableData.forEach((item) => {
              if (item.id == ids) {
                _this.$set(item, 'integrityData', _this.integrityData)
              }
            })
          }
        }
      })
    },
    tabClick(tab, event) {
      var that = this
      var tabType = tab.$attrs['data-label']
      var row = tab.$parent.$attrs['data-row'].scope.row
      if (tabType == 'base') {
        //更多信息
        this.getDetail(row)
      } else if (tabType == 'callrecord') {
        //通话记录
      }
    },
    getDetail(row) {},
    // 处理
    dealWith(row) {
      this.dialogDealWith = true
      this.dealWithForm.id = row.id
    },
    // 关闭处理
    closeDealWith() {
      this.dialogDealWith = false
      // 初始化表单
      this.$refs['dealWithForm'].resetFields()
    },
    // 确认处理
    confirmDealWith(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.dealWithForm
          // 增加用户名参数
          parames.account = that.$store.state.userinfo.accountName
          // 提交
          updateHandleResult(parames).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '处理成功！',
                type: 'success',
              })
              that.closeDealWith()
              // 刷新列表
              that.getList()
            } else {
              that.$message({
                message: res.info,
                type: 'warning',
              })
            }
          })
        } else {
          return false
        }
      })
    },
    //头部统计
    getStatis() {
      let that = this
      let parames = {
        organizationId: that.searchForm.organizationId,
        questionType: that.searchForm.questionType,
        status: that.searchForm.status, // 处理状态
        startTimeStr:
          that.searchForm.time && that.searchForm.time.length > 0
            ? that.searchForm.time[0] + ' 00:00:00'
            : '',
        endTimeStr:
          that.searchForm.time && that.searchForm.time.length > 0
            ? that.searchForm.time[1] + ' 23:59:59'
            : '',
        timeType: 13,
        isReset: 0, //实时
      }
      getKeyProblemCount(parames).then((res) => {
        that.realRiskUnitNumber_1 = res.data.orgCount
        that.realRiskUnitNumber_2 = res.data.questionCount
      })
    },
    onPreview(scope, index = 0) {
      let alarmPic = {
        pic: scope.row.picturesUrls,
        resultRegion: scope.row.picAlarmRegion,
      }
      let arr = [alarmPic]
      scope.row.aiExtInfoList.forEach((n) => {
        arr.push({
          pic: n.imageInfo.pic,
          resultRegion: JSON.stringify(n),
        })
      })
      this.originList = JSON.parse(JSON.stringify(arr))
      this.$nextTick(() => {
        this.$refs.ImageViewer.switchPic(index)
      })
    },
    formatPicUrl(val) {
      if (val.indexOf('imageView2') > -1) return val
      if (
        val.indexOf('://file.kshqfire.com') < 0 &&
        val.indexOf('://file.yx-ilink.com') < 0
      )
        return val + '?w=192&h=108'
      if (val.indexOf('imageView2') < 0)
        return val + '?imageView2/2/w/192/h/108/q/75'
      return val
    },
  },
}
</script>
<style lang="scss">
.real-sky-issue-wrap {
  .alarm-img {
    width: 192px;
    height: 108px;
    margin-right: 15px;
    object-fit: cover;
  }
  .demo-table-expand .el-form-item {
    margin-bottom: 0;
  }
  .integrity {
    margin-left: 110px;
    height: 230px;
    overflow: hidden;
    overflow-y: auto;
  }
  .weifuwei {
    padding: 2px 6px;
    background: #f6c039;
    color: #ffffff;
    margin-left: 10px;
    border-radius: 4px;
  }
  .yifuwei {
    padding: 2px 6px;
    background: #397fcf;
    color: #ffffff;
    margin-left: 10px;
    border-radius: 4px;
  }
}
</style>
